package com.neo.filter;

import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: hredis
 * @Date: 2020/10/28 20:04
 */
public class CorsFilter implements javax.servlet.Filter {


    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //使用请求头的Origin解决携带cookie的跨域问题
        String origin = request.getHeader("Origin");
        if(!StringUtils.isEmpty(origin)){
            response.addHeader("Access-Control-Allow-Origin",origin);
        }
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        //设置域检命令支持的头信息。 (支持自定义请求头)
        String headers = request.getHeader("Access-Control-Request-Headers");

        if(!StringUtils.isEmpty(headers)){
            response.addHeader("Access-Control-Allow-Headers",headers);
        } else {
            response.addHeader("Access-Control-Allow-Headers","content-type");
        }
        //设置域检命令OPTIONS的缓存时间
        response.addHeader("Access-Control-Max-Age", "3600");
        //设置缓存cookie
        response.addHeader("Access-Control-Allow-Credentials","true");

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
